﻿#include "gpio_info.h"

#include <QApplication>
#include <QDir>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>

 QMap<QString, QVector<GPIO*>> GpioSetting::gpio ;

GpioSetting::GpioSetting() {}

 void GpioSetting::init_gpio(QString comName)
{
    QVector<GPIO*> g(8);
    for( int i =0;i<8; i++)
        g[i] = new GPIO;

    gpio[comName] = g;
}

void GpioSetting::save_gpio_setting()
{
    QDir dir(qApp->applicationDirPath());
    if (!dir.exists("data"))
        dir.mkpath("data");

    //QJsonArray arrayNet;
    QJsonObject arrayMap;


   QMap<QString, QVector<GPIO*>>::Iterator  it_com = gpio.begin();

   while  (it_com !=  gpio.end())
   {
       QVector<GPIO*> g = it_com.value();
       QVector<GPIO*>::Iterator it = g.begin();
       int i = 1;
       QJsonObject array_com;
       while  (it  !=  g.end())
       {
           GPIO * gpio = *it;
           if ( gpio != nullptr)
           {
               QJsonObject objNode;
               objNode["remote_id"] = gpio->remote_id;
               objNode["remote_bit"] = gpio->remote_bit ;
               objNode["flip"] = gpio->flip ;
               objNode["input"] = gpio->mode_input ;
               objNode["level"] = gpio->level ;
               objNode["on"] = gpio->on ;

               array_com[QString("gpio_%1").arg(i)] = objNode;
           }
           i++;
           it++;
       }

       arrayMap[it_com.key()] = array_com;


       it_com++;
   }


    QByteArray bytes = QJsonDocument(arrayMap).toJson();

    QFile fileArray(QApplication::applicationDirPath() + "/data/gpio_setting.json");
    if (fileArray.open(QIODevice::WriteOnly))
    {
        fileArray.write(bytes);
        fileArray.close();
    }
}
